<template>
	<view class="login-container">
		<!-- 状态栏占位 -->
		<view class="status-bar"></view>
		
		<!-- 头部Logo区域 -->
		<view class="header">
			<view class="logo-section">
				<view class="logo-icon">🔧</view>
				<text class="app-name">智能维护系统</text>
				<text class="app-desc">让设备维护更简单</text>
			</view>
		</view>
		
		<!-- 登录表单 -->
		<view class="login-form">
			<view class="form-item">
				<view class="input-wrapper">
					<text class="input-icon">👤</text>
					<input 
						class="input-field" 
						type="text" 
						placeholder="请输入用户名" 
						v-model="loginForm.username"
					/>
				</view>
			</view>
			
			<view class="form-item">
				<view class="input-wrapper">
					<text class="input-icon">🔒</text>
					<input 
						class="input-field" 
						:type="showPassword ? 'text' : 'password'" 
						placeholder="请输入密码" 
						v-model="loginForm.password"
					/>
					<text class="password-toggle" @click="togglePassword">
						{{ showPassword ? '👁️' : '👁️‍🗨️' }}
					</text>
				</view>
			</view>
			
			<!-- 验证码输入 -->
			<view class="form-item" v-if="captchaEnabled">
				<view class="input-wrapper">
					<text class="input-icon">🔐</text>
					<input 
						class="input-field" 
						type="text" 
						placeholder="请输入验证码" 
						v-model="loginForm.code"
					/>
					<view class="captcha-image" @click="getCaptcha">
						<image v-if="captchaImage" :src="captchaImage" class="captcha-img"></image>
						<text v-else class="captcha-placeholder">点击获取</text>
					</view>
				</view>
			</view>
			
			<!-- 测试账号提示 -->
			<view class="test-accounts">
				<text class="test-title">测试账号：</text>
				<view class="account-list">
					<text class="account-item" @click="fillAccount('admin', 'admin123')">admin / admin123 (管理员)</text>
          <text class="account-item" @click="fillAccount('maintenance_foreman', '123456')">maintenance_foreman / 123456 维修工长</text>
          <text class="account-item" @click="fillAccount('maintenance_manager', '123456')">maintenance_manager / 123456 维修主管</text>
					<text class="account-item" @click="fillAccount('maintenance_worker', '123456')">maintenance_worker / 123456 (维修人员)</text>
					<text class="account-item" @click="fillAccount('warehouse_manager', '123456')">warehouse_manager / 123456 (仓库管理员)</text>
				</view>
			</view>
			
			<view class="form-options">
				<view class="remember-me">
					<text class="checkbox" :class="{ active: rememberMe }" @click="toggleRemember">
						{{ rememberMe ? '☑️' : '☐' }}
					</text>
					<text class="remember-text">记住密码</text>
				</view>
				<text class="forgot-password" @click="forgotPassword">忘记密码？</text>
			</view>
			
			<button class="login-btn" @click="doLogin" :disabled="loading">
				{{ loading ? '登录中...' : '登录' }}
			</button>
		</view>
		
		<!-- 底部信息 -->
		<view class="footer">
			<text class="footer-text">© 2025 智能维护系统</text>
		</view>
	</view>
</template>

<script>
	import apiConfig from '@/config/api.js'
	import permissionManager from '@/utils/permission.js'
	
	export default {
		data() {
			return {
				loginForm: {
					username: '',
					password: '',
					code: '',
					uuid: ''
				},
				showPassword: false,
				rememberMe: false,
				loading: false,
				captchaEnabled: false,
				captchaImage: '',
				testMode: true // 测试模式，跳过验证码
			}
		},
		onLoad() {
			// 检查是否已登录
			this.checkLoginStatus();
			// 加载记住的用户名
			this.loadRememberedUsername();
			// 获取验证码
			this.getCaptcha();
		},
		methods: {
			// 检查登录状态
			checkLoginStatus() {
				const token = uni.getStorageSync('token');
				if (token) {
					// 已登录，跳转到工作台
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
			},
			
			// 加载记住的用户名
			loadRememberedUsername() {
				const username = uni.getStorageSync('username');
				if (username) {
					this.loginForm.username = username;
					this.rememberMe = true;
				}
			},
			
			// 切换密码显示
			togglePassword() {
				this.showPassword = !this.showPassword;
			},
			
			// 切换记住密码
			toggleRemember() {
				this.rememberMe = !this.rememberMe;
			},
			
			// 忘记密码
			forgotPassword() {
				uni.showModal({
					title: '忘记密码',
					content: '请联系系统管理员重置密码',
					showCancel: false
				});
			},
			
			// 填充测试账号
			fillAccount(username, password) {
				this.loginForm.username = username;
				this.loginForm.password = password;
			},
			
			// 获取验证码
			async getCaptcha() {
				try {
					const response = await this.callCaptchaAPI();
					if (response.captchaEnabled) {
						this.captchaEnabled = true;
						this.captchaImage = 'data:image/jpeg;base64,' + response.img;
						this.loginForm.uuid = response.uuid;
						console.log('验证码获取成功，UUID:', response.uuid);
					} else {
						this.captchaEnabled = false;
						console.log('验证码已禁用');
					}
				} catch (error) {
					console.error('获取验证码失败:', error);
					// 如果获取验证码失败，暂时禁用验证码以便测试
					this.captchaEnabled = false;
					console.log('验证码获取失败，已禁用验证码验证');
				}
			},
			
			// 调用验证码API
			callCaptchaAPI() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://127.0.0.1:8081/captchaImage',
						method: 'GET',
						timeout: 10000,
						success: (response) => {
							console.log('验证码响应:', response);
							if (response.statusCode === 200 && response.data.code === 200) {
								resolve(response.data);
							} else {
								reject(new Error(response.data.msg || '获取验证码失败'));
							}
						},
						fail: (error) => {
							console.error('获取验证码请求失败:', error);
							reject(new Error('网络请求失败'));
						}
					});
				});
			},
			
			// 执行登录
			async doLogin() {
				// 表单验证
				if (!this.loginForm.username) {
					uni.showToast({
						title: '请输入用户名',
						icon: 'none'
					});
					return;
				}
				
				if (!this.loginForm.password) {
					uni.showToast({
						title: '请输入密码',
						icon: 'none'
					});
					return;
				}
				
				if (this.captchaEnabled && !this.testMode && !this.loginForm.code) {
					uni.showToast({
						title: '请输入验证码',
						icon: 'none'
					});
					return;
				}
				
				this.loading = true;
				
				try {
					// 直接调用后端登录接口
					const loginResult = await this.callLoginAPI(
						this.loginForm.username, 
						this.loginForm.password,
						this.loginForm.code,
						this.loginForm.uuid
					);
					
					// 保存token
					if (loginResult.token) {
						uni.setStorageSync('token', loginResult.token);
						
						// 获取用户信息
						const userInfoResult = await this.callUserInfoAPI();
						if (userInfoResult.user) {
							const userInfo = {
								username: userInfoResult.user.userName,
								name: userInfoResult.user.nickName || userInfoResult.user.userName,
								role: userInfoResult.roles ? userInfoResult.roles[0] : '用户',
								avatar: userInfoResult.user.avatar || '/static/个人头像.png',
								userId: userInfoResult.user.userId,
								permissions: userInfoResult.permissions || [],
								roles: userInfoResult.roles || [],
								user: userInfoResult.user
							};
							
							// 保存用户信息
							uni.setStorageSync('userInfo', userInfo);
							
							// 设置权限管理器
							permissionManager.setUserInfo(userInfo);
							
							console.log('用户登录成功，角色:', userInfo.roles);
						}
						
						// 保存记住的用户名
						if (this.rememberMe) {
							uni.setStorageSync('username', this.loginForm.username);
						} else {
							uni.removeStorageSync('username');
						}
						
						// 登录成功
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						
						// 跳转到工作台
						setTimeout(() => {
							// 根据用户角色重定向到不同的首页
							const homePage = permissionManager.getRoleHomePage();
							uni.reLaunch({
								url: homePage
							});
						}, 1500);
					} else {
						throw new Error('登录失败，未获取到token');
					}
					
				} catch (error) {
					console.error('登录失败:', error);
					uni.showToast({
						title: error.message || '登录失败，请检查用户名和密码',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 调用登录API
			callLoginAPI(username, password, code, uuid) {
				return new Promise((resolve, reject) => {
					uni.request({
						url: 'http://127.0.0.1:8081/login',
						method: 'POST',
						data: {
							username: username,
							password: password,
							code: code || '',
							uuid: uuid || ''
						},
						header: {
							'Content-Type': 'application/json'
						},
						timeout: 10000,
						success: (response) => {
							console.log('登录响应:', response);
							if (response.statusCode === 200) {
								if (response.data.code === 200) {
									resolve(response.data);
								} else {
									reject(new Error(response.data.msg || '登录失败'));
								}
							} else {
								reject(new Error(`请求失败: ${response.statusCode}`));
							}
						},
						fail: (error) => {
							console.error('登录请求失败:', error);
							reject(new Error('网络请求失败'));
						}
					});
				});
			},
			
			// 调用获取用户信息API
			callUserInfoAPI() {
				return new Promise((resolve, reject) => {
					const token = uni.getStorageSync('token');
					uni.request({
						url: 'http://127.0.0.1:8081/getInfo',
						method: 'GET',
						header: {
							'Authorization': `Bearer ${token}`,
							'Content-Type': 'application/json'
						},
						timeout: 10000,
						success: (response) => {
							console.log('用户信息响应:', response);
							if (response.statusCode === 200) {
								if (response.data.code === 200) {
									resolve(response.data);
								} else {
									reject(new Error(response.data.msg || '获取用户信息失败'));
								}
							} else {
								reject(new Error(`请求失败: ${response.statusCode}`));
							}
						},
						fail: (error) => {
							console.error('获取用户信息失败:', error);
							reject(new Error('网络请求失败'));
						}
					});
				});
			}
		}
	}
</script>

<style>
	.login-container {
		min-height: 100vh;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		display: flex;
		flex-direction: column;
	}
	
	.status-bar {
		height: 64rpx;
	}
	
	.header {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 0 60rpx;
	}
	
	.logo-section {
		text-align: center;
		color: white;
	}
	
	.logo-icon {
		font-size: 120rpx;
		margin-bottom: 40rpx;
	}
	
	.app-name {
		display: block;
		font-size: 48rpx;
		font-weight: bold;
		margin-bottom: 20rpx;
	}
	
	.app-desc {
		display: block;
		font-size: 28rpx;
		opacity: 0.9;
	}
	
	.login-form {
		background-color: white;
		border-radius: 40rpx 40rpx 0 0;
		padding: 60rpx 60rpx 40rpx;
	}
	
	.form-item {
		margin-bottom: 40rpx;
	}
	
	.input-wrapper {
		display: flex;
		align-items: center;
		background-color: #f8f9fa;
		border-radius: 20rpx;
		padding: 0 30rpx;
		height: 100rpx;
		border: 2rpx solid #e9ecef;
	}
	
	.input-icon {
		font-size: 32rpx;
		margin-right: 20rpx;
		color: #6c757d;
	}
	
	.input-field {
		flex: 1;
		font-size: 32rpx;
		color: #333;
	}
	
	.password-toggle {
		font-size: 32rpx;
		color: #6c757d;
		padding: 10rpx;
	}
	
	.captcha-image {
		width: 200rpx;
		height: 80rpx;
		margin-left: 20rpx;
		border-radius: 10rpx;
		overflow: hidden;
		background-color: #f8f9fa;
		display: flex;
		align-items: center;
		justify-content: center;
		border: 1rpx solid #e9ecef;
	}
	
	.captcha-img {
		width: 100%;
		height: 100%;
		display: block;
	}
	
	.captcha-placeholder {
		font-size: 24rpx;
		color: #6c757d;
	}
	
	.test-accounts {
		margin: 30rpx 0;
		padding: 20rpx;
		background-color: #f8f9fa;
		border-radius: 15rpx;
		border: 1rpx solid #e9ecef;
	}
	
	.test-title {
		font-size: 24rpx;
		color: #666;
		margin-bottom: 15rpx;
		display: block;
	}
	
	.account-list {
		display: flex;
		flex-direction: column;
		gap: 10rpx;
	}
	
	.account-item {
		font-size: 24rpx;
		color: #007aff;
		padding: 10rpx 15rpx;
		background-color: white;
		border-radius: 8rpx;
		border: 1rpx solid #e0e0e0;
		text-align: center;
	}
	
	.account-item:active {
		background-color: #f0f0f0;
	}
	
	.form-options {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 60rpx;
	}
	
	.remember-me {
		display: flex;
		align-items: center;
	}
	
	.checkbox {
		font-size: 32rpx;
		margin-right: 15rpx;
	}
	
	.checkbox.active {
		color: #667eea;
	}
	
	.remember-text {
		font-size: 28rpx;
		color: #6c757d;
	}
	
	.forgot-password {
		font-size: 28rpx;
		color: #667eea;
	}
	
	.login-btn {
		width: 100%;
		height: 100rpx;
		background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
		color: white;
		font-size: 36rpx;
		font-weight: bold;
		border-radius: 20rpx;
		border: none;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.login-btn:disabled {
		opacity: 0.6;
	}
	
	.footer {
		text-align: center;
		padding: 40rpx;
		background-color: white;
	}
	
	.footer-text {
		font-size: 24rpx;
		color: #999;
	}
</style>
